package com.lcd.ssm.service.impl;

import com.lcd.ssm.domain.Employee;
import com.lcd.ssm.domain.Permission;
import com.lcd.ssm.domain.Role;
import com.lcd.ssm.mapper.RoleMapper;
import com.lcd.ssm.page.PageResult;
import com.lcd.ssm.query.RoleQueryObject;
import com.lcd.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * lcd  2020/4/30
 * Description:
 */
@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public int deleteByPrimaryKey(Long id) {
        return roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Role record) {
        int insert = roleMapper.insert(record);
        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            roleMapper.insertRelationWithPermission(record.getId(), permission.getId());
        }
        return insert;
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Role record) {
        int i = roleMapper.updateByPrimaryKey(record);
        //删除旧的关系
        roleMapper.deleteRelationPermission(record);
        //保存新的关系
        List<Permission> permissions = record.getPermissions();
        for (Permission permission : permissions) {
            roleMapper.insertRelationWithPermission(record.getId(), permission.getId());
        }

        return i;
    }

    @Override
    public PageResult queryForPage(RoleQueryObject qo) {
        Long count=roleMapper.queryForPageCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.emptyList());
        }
        List<Role> list=roleMapper.queryForPage(qo);
        return new PageResult(count.intValue(),list);
    }


}
